<!-- 创作中心——上传文件 -->
<template>
	<view class="flex-column margin-top_60rpx">
		<!-- <view>tempFiles:{{tempFiles}}</view> -->
		<view class="upload-cls flex-column" @click="uploadClick()">
			<image class="upload-img" :src="cloudUploadglay"></image>
			<uni-icons type="cloud-upload" size="30"></uni-icons>


			<view class="upload-text">点击上传文件</view>
		</view>
		<view class="v-hint">
			只能上传.mp4 / .3gp / .mov文件，且不超过{{ (Number(upload_allow_size)/ 1024 / 1024).toFixed(2) }}M,视频单次上传最多8个
			<!-- 只能上传.mp4 / .3gp / .mov文件，且不超过50M (视频 单次上传最多5个) -->
		</view>
		<scroll-view :scroll-y="true" class="scroll-cls" v-if="tempFiles.length>0">
			<block v-for="(i, j) in tempFiles" :key="j">
				<view class="flex-between file-cls">
					<view>{{ i.tempFilePath }}</view>
					<uv-icon class=" padding-right_10rpx icon-cls p-right10" name="close-circle"
						@click="delFiles(j)"></uv-icon>
				</view>
			</block>
		</scroll-view>

		<view class="flex-align-center btn-cls">
			<view class="confirm-cls flex" @click="startUploading">开始上传</view>
			<view class="return-cls flex" @click="returnClick">返回</view>
		</view>
	</view>
</template>

<script>
	const base64 = require('@/utils/ali-oos/base64.js'); //Base64,hmac,sha1,crypto相关算法
	require('@/utils/ali-oos/hmac.js');
	require('@/utils/ali-oos/sha1.js');
	const Crypto = require('@/utils/ali-oos/crypto.js');
	export default {
		data() {
			return {

				isPiece: '', //是否成片管理 1是,成片限制视频大小30M
				numCount: 0, //上传次数汇总
				info: {},
				tempFiles: [], //上传获取到的文件数组
				/* 上传视频start */
				formData: {
					key: '',
					policy: '',
					OSSAccessKeyId: '',
					signature: '',
					success_action_status: '200'
				},

				policyText: {
					expiration: '2050-01-01T12:00:00.000Z', //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
					conditions: [
						['content-length-range', 0, Number(uni.getStorageSync('upload_allow_size'))] // 设置上传文件的大小限制(104857600为：100MB，31457280为30MB)
					]
				},
                 upload_allow_size: uni.getStorageSync('upload_allow_size'),
				upPicUrl2: '',
				ossUrl: '', //上传阿里云返回视频路径
				/* 上传视频end */

				points: 0,
				parentId: 0, // 成片父级文件夹id
				videoReview: 0, //视频审核点数
				remainingPoints: 0, //剩余可用点数
				tempFilesRes:'',
				setObj: {}, //商家端查询代理基础设置

			};
		},
		computed: {
			// 上传类型
			isType: function() {
				return function(typeId) {
					console.log('typeId', typeId);
					let isType = '';
					/*1:视频 2:音频 3:台本 4:图片*/
					if (typeId == 1) {

						isType = '.mp4 / .3gp / .mov';
					}
					if (typeId == 2) {
						isType = '.mp3 / .m4a / .aac';
					}
					if (typeId == 3) {
						isType = '.mp3 ';
					}
					if (typeId == 4) {
						isType = '.jpg / .jpeg / .png';
					}
					console.log('isType', isType);
					return isType;
				};
			}
		},
		onLoad(options) {
			this.tempFiles = []; //第一次进入 置空
			this.isPiece = '';
			// 成片文件夹进入,则只能上传视频
			// if (options.isPiece && options.isPiece == 1) {
			// 	this.isPiece = options.isPiece;
			// 	this.info.type = 1;
			// 	this.parentId = options.parentId;
			// }
			// info.type  1:视频 2:音频 3:台本 4:图片
			// info.id    父级文件夹id
			console.log(JSON.parse(options.info), '===')
			if (options.info) {
				this.info = JSON.parse(options.info)
			}

			if (this.info.type == 1 || (options.isPiece && options.isPiece == 1)) {
				// this.queryPoints();
			}
			this.set();
			// this.uploadSetFn()
			// this.getSet();
			console.log('options', options, 'this.info', this.info);
		},
		onShow() {},
		methods: {

			//商家端查询代理基础设置——查询接口
			async getSet() {
				const result = await this.$http.post({
					url: this.$api.getMerchantSystemConfig,
					data: {
						id: uni.getStorageSync('merchantId')
					}
				});
				if (result.code == 2000) {
					this.setObj = result.data;
				}
			},
			// 查询点数（需对接）
			async queryPoints() {
				// 查询剩余可用点数
				const result = await this.$http.post({
					url: this.$api.getDianShu,
					data: {
						id: uni.getStorageSync('merchantId')
					}
				});
				if (result.code == 2000) {
					console.log('查询可用点数result', result);
					if (result.data) {
						this.remainingPoints = result.data.counts; // 剩余点数
					}
				} else {
					this.$sun.toast(result.msg, 'none');
				}
				// 查询oem，发布视频点数
				const result2 = await this.$http.post({
					url: this.$api.queryOemPoint,
					data: {
						id: uni.getStorageSync('merchantId')
					}
				});
				if (result2.code == 2000) {
					if (result2.data) {
						console.log('发布频点数result2', result2);
						this.points = Number(result2.data.replyComment); // 成片扣点点数
						// videoReview 视频审核点数
						this.videoReview = result2.data.videoReview ? Number(result2.data.videoReview) : 0;
					}
				} else {
					this.$sun.toast(result2.msg, 'none');
				}
			},
			/*  阿里云设置  */
			async set() {
				const result = await this.$http.get({
					url: this.$api.uploadSet,

				});
				if (result.errno == 0) {
					// accessKey 阿里云key秘钥 accessId 阿里云id
					console.log('result', result);
					this.upPicUrl2 = 'https://' + result.data.alioss_domain;
					this.formData.OSSAccessKeyId = result.data.alioss_access_key_id;
					this.formData.policy = base64.encode(JSON.stringify(this.policyText));
					let message = this.formData.policy;
					let bytes = Crypto.HMAC(Crypto.SHA1, message, result.data.alioss_access_key_secret, {
						asBytes: true
					});
					this.formData.signature = Crypto.util.bytesToBase64(bytes);

					console.log('------------formData', this.formData);
				}
			},

			// “上传文件” 点击事件
			// info.type  1:视频 2:音频 3:台本 4:图片
			uploadClick() {
				//选择音频文件

				if (this.info.type == 1) {
					uni.chooseMedia({
						// 如果type属性和extension同时存在，例如{type:'image',extension:['.png','.jpg']}，则会选择image/png,image/jpg文件
						// 如果只配置extension属性，例如{extension:['.doc','.xlsx','.docx']}，则会选择.doc,.xlsx,.docx文件，详情见accept属性
						// 在微信环境中，如果type="all"，则extension属性失效
						count: 8, //选取的文件个数限制
						// type: that.info.type==4?'image':'video',//all	从所有文件选择    video	只能选择视频文件   image	只能选择图片文件
						mediaType: ['video'], //all	从所有文件选择    video	只能选择视频文件   image	只能选择图片文件
						sourceType: ['album', 'camera'],
						compressed:false,
						camera: 'back',
						sizeType:['original'],
						maxDuration: 30,
						success: res => {
							let allLength = this.tempFiles.length + res.tempFiles.length;
							console.log('点击上传事件res.tempFiles', res.tempFiles.length, 'that.tempFiles', this
								.tempFiles.length, 'allLength', allLength);
							if (allLength > 8) {
								this.$sun.toast('当前限制选择 8 个文件，本次选择了 ' + res.tempFiles.length + ' 个文件');
								return;
							}
							this.tempFiles = [...this.tempFiles, ...res.tempFiles]; //要上传的文件
							this.tempFilesRes = [res];
							console.log('tempFiles======', this.tempFiles, 'res', res);

							// 获取时长


							// 测试，需删除
							/* uni.showModal({
								title: '提示',
								content: '确定要删除该摄像头吗'+that.tempFiles,
								success: function(res) {
									if (res.confirm) {
										// 删除指定下标
										this.$sun.toast('删除成功!');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							}); */
						},
						fail(error) {
							console.error('选择文件失败:', error);
							// 处理文件选择失败的逻辑
						}
					});

				}

			},
			// 开始上传
			async startUploading() {
				console.log(this.tempFiles)






				// let that = this;
				this.numCount = 0;
				if (this.tempFiles.length <= 0) {
					this.$sun.toast('请先上传文件', 'none');
					return;
				}


				let isLt = true;
				let numSize =  Number(uni.getStorageSync('upload_allow_size'))/ 1024 / 1024;
				for (let i = 0; i < this.tempFiles.length; i++) {
					// 判断是否小于2mb
					if (this.tempFiles[i].size / 1024 / 1024 > numSize) {
						isLt = false;
					}
				}

				for (let i = 0; i < this.tempFiles.length; i++) {
					// 判断是否小于2mb
					if (this.tempFiles[i].duration < 15) {

						this.tempFiles.splice(i, 1);
						this.$sun.toast('请上传大于15秒及以上的视频', 'none');
						return;
					}
				}

				if (!isLt) {
					for (let i = 0; i < this.tempFiles.length; i++) {
						// 判断是否小于2mb
						if (this.tempFiles[i].size / 1024 / 1024 > numSize) {
							console.log('进入删除', i);
							this.tempFiles.splice(i, 1);
						}
					}
					this.$sun.toast('请上传小于' + numSize.toFixed(2) + 'MB文件', 'none');
					return;
				}
				console.log('this.remainingPoints,this.points*this.tempFiles.length', this.remainingPoints, this
					.points, this.tempFiles.length, 'this.videoReview', this.videoReview);

				//contentReview=1代表“视频审核”开启
				// if (this.isPiece == 1 ) {
				// 	console.log('Number(this.points + this.videoReview)*this.tempFiles.length', Number(this.points + this.videoReview) * this.tempFiles.length);
				// 	if(this.setObj.contentReview == 1){
				// 		if (Number(this.remainingPoints) < Number(this.points + this.videoReview) * this.tempFiles.length) {
				// 			this.$sun.toast('剩余点数不足上传成片', 'none');
				// 			return;
				// 		}
				// 	}
				// 	else{
				// 		if (Number(this.remainingPoints) < Number(this.points) * this.tempFiles.length) {
				// 			this.$sun.toast('剩余点数不足上传成片', 'none');
				// 			return;
				// 		}
				// 	}
				// }
				// //  视频上传 判断“审核点数”总计算
				// if (this.isPiece != 1 && this.info.type == 1 && this.setObj.contentReview == 1 ||
				// this.isPiece != 1 && this.info.type == 4 && this.setObj.contentReview == 1) {
				// 	console.log('Number(this.videoReview)*this.tempFiles.length222', Number(this.videoReview) * this.tempFiles.length);
				// 	if (Number(this.remainingPoints) < Number(this.videoReview) * this.tempFiles.length) {
				// 		let hint = this.info.type == 1? '视频': '图片'
				// 		this.$sun.toast('剩余点数不足上传'+hint+'审核', 'none');
				// 		return;
				// 	}
				// }

				uni.showLoading({
					title: '上传中...'
				});
				for (let i = 0; i < this.tempFiles.length; i++) {
					
					const extension = this.tempFiles[i].tempFilePath.split('.').pop().toLowerCase();
					
					this.formData.key = new Date().getTime() + Math.floor(Math.random() * 150) + '.' + extension;

					console.log('this.formData.key', this.formData.key, 'this.tempFiles[i].name', this.tempFiles[i]
						.name, 'this.tempFiles[i]', this.tempFiles[i]);
					
					// this.tempFiles[i].tempFilePath	
					
					// fileUrl放在上传（uploadFile）内，则只能获取到最后一个值
					let fileUrl = this.upPicUrl2 + '/' + this.formData.key;
					let formData = {
						...this.formData
					}; //需要这样赋值，否则for循环传值一致
					// 音频 audio/mpeg   图片 image/png

					let type = this.tempFiles[i].type; //需要这样赋值，否则for循环传值一致
					console.log('fileUrl, type123', fileUrl, type, 'this.formData', this.formData);
					uni.uploadFile({
						name: 'file', //文件上传的name值
						url: this.upPicUrl2, //接口地址
						formData: formData, //上传额外携带的参数
						filePath: this.tempFiles[i].tempFilePath, //临时路径
						success: uploadFileRes => {
							console.log('this.formData222222', this.formData, uploadFileRes);
							if (uploadFileRes.statusCode != 200) {
								uni.showToast({
									title: '上传失败 : ' + uploadFileRes.data,
									icon: 'none'
								});
							} else {
								this.numCount++;


								// if (this.isPiece == 1) {
								// 	this.pieceRegisterMedias(fileUrl, type);
								// } else {
								this.registerMedias(fileUrl, type, this.tempFiles[i].tempFilePath);
								// }
							}
						},
						fail: e => {
							uni.showToast({
								title: '上传失败==>' + e,
								icon: 'none'
							});
						}
					});
				}
			},
			// 注册媒资
			async registerMedias(url, type, name) {
				console.log('注册媒资 this.numCount', this.numCount);

				const result = await this.$http.post({
					url: this.$api.fileSave,
					data: {
						folder_id: this.info.id, //父级id
						file: url, //上传阿里云生成的地址

						uid: uni.getStorageSync('uid'),
						name: name,
						type: this.info.typeSource,
						cover: url + '?x-oss-process=video/snapshot,t_0,f_jpg'



					}
				});
				if (result.errno == 0) {
					console.log('注册媒资result342332423', result.data, 'numCount', this.numCount);
					if (this.numCount == this.tempFiles.length) {
						uni.hideLoading(); //清除加载中

						this.tempFiles = [];
						setTimeout(() => {
							this.$sun.toast('上传成功');
						}, 500)
					}
				} else {
					uni.hideLoading(); //清除加载中
					setTimeout(() => {
						this.$sun.toast(result.message, 'none');
					}, 200)
					console.log('失败(result======', result);

				}
			},

			// 注册成片
			async pieceRegisterMedias(url, type) {
				console.log('注册媒资 this.numCount', this.numCount);
				const result = await this.$http.post({
					url: this.$api.saveVideoPoints,
					data: {
						outUrl: url, //上传阿里云生成的地址
						isPublish: 0, //是否发布 0未使用1已使用(默认未使用)
						username: uni.getStorageSync('merchantCode'),
						state: 'Success', //任务状态
						productPolderId: this.parentId, //文件id
						merchantId: uni.getStorageSync('merchantId'), // 商家id
						checkNumber: this.points // + this.videoReview计算的成片总点数
					}
				});
				if (result.errno == 0) {
					console.log('注册媒资result342332423', result.data, 'numCount', this.numCount);
					if (this.numCount == this.tempFiles.length) {
						this.$sun.toast('上传成功');
						this.tempFiles = [];
						uni.hideLoading(); //清除加载中
					}
				} else {
					console.log('失败(result======', result);
					this.$sun.toast(result.message, 'none');
				}
			},

			// 删除
			delFiles(index) {
				this.tempFiles.splice(index, 1);
			},
			// 返回
			returnClick() {
				this.$sun.navBack();
			}
		}
	};
</script>

<style lang="less">
	page {
		background-color: #f7f7f7;
	}

	.upload-cls {
		width: 682rpx;
		height: 474rpx;
		overflow: hidden;
		margin-top: 10rpx;
		margin-right: 11rpx;
		border: 1px dashed #e9e9e9;
		background: #fff;
		font-size: 0;
		position: relative;
		border-radius: 10rpx;
	}

	.upload-img {
		width: 90rpx;
		height: 90rpx;
	}

	.upload-text {
		font-size: 32rpx;
		line-height: 56rpx;
		text-align: center;
		color: #999999;
		width: 100%;
	}

	.v-hint {
		color: #999;
		font-size: 28rpx;
		padding: 50rpx 34rpx;
		// padding: 50rpx 34rpx 160rpx;
	}

	.scroll-cls {
		height: 500rpx;
		width: calc(100% - 120rpx);
		background: #eaeaea;
		padding: 20rpx 0 0;
		border-radius: 10rpx;

		.file-cls {
			margin: 0rpx 10rpx 20rpx 40rpx;
			color: #666;

			view {
				// width: 100%;
				overflow: hidden;
			}

			i {
				padding: 20rpx;
			}
		}
	}

	.btn-cls {
		z-index: 999;
		position: fixed;
		left: 0;
		bottom: 0;
		padding: 44rpx;
		background-color: #f7f7f7;

		// 开始上传
		.confirm-cls {
			width: 448rpx;
			height: 88rpx;
			border-radius: 20rpx 0rpx 0rpx 20rpx;
			background: #1e6ceb;
			color: #fff;

			font-size: 32rpx;
		}

		// 返回
		.return-cls {
			color: #5f5d5d;
			font-size: 32rpx;
			width: 212rpx;
			height: 88rpx;
			border-radius: 0rpx 20rpx 20rpx 0rpx;
			border: 2rpx solid #efefef;
			background: #fff;
		}
	}
</style>